package com.inspire.sms.health;

import com.inspire.sms.constant.Columns;
import com.inspire.sms.model.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import com.inspire.sms.config.SMSHealthConfig;


/**
 * @author inspire
 * @apiNote 健康监控
 */
@Component
public class SMSHealthIndicator implements HealthIndicator {

	private static final Logger logger = LoggerFactory.getLogger(SMSHealthIndicator.class);
	/**
	 * 统计样本
	 */
	private final boolean[] samples;

	/**
	 * 统计发送总量
	 */
	private long count = 0;

	/**
	 * 短信发送成功率临界值
	 */
	private final float threshold;

	/**
	 * 上一次发送失败原因
	 */
	private String lastFailCode = null;

	public SMSHealthIndicator(SMSHealthConfig config) {
		samples = new boolean[config.getSamples()];
		threshold = config.getThreshold();
	}

	@Override
	public synchronized Health health() {
		if (count < samples.length) {
			return Health.unknown().withDetail("count", count).build();
		} else {
			int success = 0;
			for (boolean sample : samples) {
				if (sample) {
					success++;
				}
			}
			float ratio = (success * 100 / samples.length) / 100f;
			logger.info("ratio: {}",ratio);
			if (ratio < threshold) {
				return Health.down().withDetail("count", count).withDetail("ratio", ratio)
						.withDetail("lastFailCode", lastFailCode).build();
			} else {
				return Health.up().withDetail("count", count).withDetail("ratio", ratio).build();
			}
		}
	}

	public synchronized void addSample(Message message) {
		logger.info("message.getSendStatus: {}",message.getSendStatus());
		System.out.println();
		if (message.getSendStatus() == Columns.SendStatus.SENDING) {
			logger.info("发送成功");
			int index = (int) (count++ % samples.length);
			samples[index] = true;
		} else if (message.getSendStatus() == Columns.SendStatus.FAILURE) {

			lastFailCode = message.getFailCode();
			int index = (int) (count++ % samples.length);
			samples[index] = false;
		}
	}

}
